package com.lovetemperature.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.lovetemperature.dao.Dao;

public class DaoImpl<T> implements Dao<T>{
	private SessionFactory sessionFactory;
	private T obj;
	
	private String getTypeString(){
		return obj.getClass().getSimpleName();
	}

	public DaoImpl() {
		initSessionFactory();
	}
	
	public DaoImpl(T obj){
		this.obj = obj;
		initSessionFactory();
	}
	
	private void initSessionFactory(){
		this.sessionFactory = new Configuration().configure().buildSessionFactory();
	}

	@Override
	public List<T> findAll() {
		Session session = sessionFactory.openSession();
		session.beginTransaction();

		Query query = session.createQuery("from " + this.getTypeString());
		List<T> result = query.list();

		session.getTransaction().commit();
		session.flush();
		session.close();
		return result;
	}

	@Override
	public void save(T obj) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();

		session.save(obj);

		session.getTransaction().commit();
		session.flush();
		session.close();
	}

	@Override
	public void delect(T obj) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		session.delete(obj);

		session.getTransaction().commit();
		session.flush();
		session.close();
	}

	@Override
	public T findById(Long id) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();

		T result = (T)session.get(obj.getClass(), id);

		session.getTransaction().commit();
		session.flush();
		session.close();
		return result;
	}
	
	@Override
	public List<T> findByField(String field, String value){
		Session session = sessionFactory.openSession();
		session.beginTransaction();

		String hql = "from " + this.getTypeString() + " where "+ field +" = '" + value +"'";
		System.out.println(hql);
		Query query = session.createQuery(hql);
		List<T> result = query.list();

		session.getTransaction().commit();
		session.flush();
		session.close();
		return result;
	}

	@Override
	public List<T> query(String hql) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();

		Query query = session.createQuery(hql);
		List<T> result = query.list();

		session.getTransaction().commit();
		session.flush();
		session.close();
		return result;
	}

	public T getObj() {
		return obj;
	}

	public void setObj(T obj) {
		this.obj = obj;
	}

	@Override
	public void update(T obj) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();

		session.merge(obj);

		session.getTransaction().commit();
		session.flush();
		session.close();
	}
}
